<?php

namespace app\admin\controller\photo;

use app\common\controller\Backend;
use app\admin\model\photo\Related as RelatedModel;
use Think\Db;
use OSS\OssClient;

use OSS\Core\OssException;
/**
 * 
 *
 * @icon fa fa-circle-o
 */
class Itinerary extends Backend
{

    /**
     * Itinerary模型对象
     * @var \app\admin\model\photo\Itinerary
     */
    protected $model = null;
    protected $noNeedRight = ['export'];
    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\photo\Itinerary;
         $this->RelatedModel = new \app\admin\model\photo\Related;
        $this->view->assign("statusList", $this->model->getStatusList());
    }
    /**
     * 查看
     *
     * @return string|Json
     * @throws \think\Exception
     * @throws DbException
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        $list = $this->model
        ->with(['route','user'])
            ->where($where)
            ->order($sort, $order)
            ->paginate($limit);
        foreach ($list as $k => &$v) {
           
            $v['file_count'] = RelatedModel::where('itinerary_id',$v['id'])->count();
            $v['number_count'] =RelatedModel::where('itinerary_id',$v['id'])->group('user_id')->count();
        }
        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }
    
    /**
     * 查看列表
     */
    public function index1()
    {
        if ($this->request->isAjax()) {

            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            // dump($where);
            $total = $this->RelatedModel
                ->where($where)

                ->order($sort, $order)->fetchSql(false)
                ->count();
            $list = $this->RelatedModel
                ->with(['file','user','itinerary'])
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)->fetchSql(false)
                ->select();
                  $adminModel=new \app\admin\model\photo\City();
            foreach ($list as &$row){
                $row['city']=$adminModel->where('id',$row->city_id)->value('name');
                
            }
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    public function export($ids)
    {
       
        $picAllArr = array_column(db::table('fa_photo_file')->whereIn('id',$ids)->field('url')->select(), 'url');
       
       $accessKeyId = 'LTAI5t8zPL2aEpp1Gm7D6Guj';
        $accessKeySecret = '2VXvbgLKaFiXBZBJYyKrw57t2girJY';
        $endpoint = 'oss-cn-qingdao.aliyuncs.com';
        $bucket = 'zhangluxiaochengxu';
        //  $config = Config::get('aliyun_oss');
           $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
           
        $ossClient->createBucket($bucket);
        
       
         
         error_reporting(E_ALL);
		ini_set('display_errors', true);
        
		$zip = new \ZipArchive;
		$tmpFileName = './tmpzip' . mt_rand(100, 999);
		$res = $zip->open($tmpFileName, \ZipArchive::CREATE);
	 //获取object内容
	    foreach ($picAllArr as $file){
	       
	       $objectName = substr($file,1);
	        
            $object = $ossClient->getObject($bucket, $objectName);
            $file = $objectName;
            
    		$zip->addFromString($file, $object);
	    }
	   
	    
	    $zip->close();
	    $tarFile = date('His') . mt_rand(1000, 9999) . '.zip';
	
		$fileSize = filesize($tmpFileName);
		$fp = fopen($tmpFileName, "r");
		header("Content-type: application/octet-stream");
		header("Accept-Ranges: bytes");
		header("Accept-Length: " . $fileSize);
		header("Content-Disposition: attachment; filename=" . $tarFile); 
		$buffer = 1024;
		$fileCount = 0;
		while (!feof($fp) && $fileCount < $fileSize) {
			$fileCon = fread($fp, $buffer);
			$fileCount += $buffer;
			echo $fileCon;
		}
		fclose($fp);
		unlink($tmpFileName);


 
        

    }
    
    

    public function export1($ids)
    {
	    $picAllArr = array_column(Db::table('fa_photo_file')->whereIn('id',$ids)->field('fullurl')->select(), 'fullurl');
        $tmpDir = '/www/wwwroot/demo.dzqiji.com/public/uploads'; // 类似于/www/public/upload/

        if (!file_exists($tmpDir)) {
            //创建文件夹
            mkdir($tmpDir, 0777, true);
        }

        $zipName = date('His') . mt_rand(1000, 9999) . '.zip'; // 压缩包文件名
        $zipNameUrl = $tmpDir . $zipName; // 文件路径

        // 生成文件
        $zip = new \ZipArchive();
        if ($zip->open($zipNameUrl, \ZipArchive::OVERWRITE) !== true) {
            //OVERWRITE 参数会覆写压缩包的文件 文件必须已经存在
            if ($zip->open($zipNameUrl, \ZipArchive::CREATE) !== true) {
                // 文件不存在则生成一个新的文件 用CREATE打开文件会追加内容至zip
                return  '下载失败，文件夹不存在';
            }
        }
       
        foreach ($picAllArr as $file) {
             
            //判断图片是否存在
            $isFile = $this->checkFileExists($file);
            if (!$isFile) {
                continue;
            }
            //抓取图片内容
            $fileContent = file_get_contents($file);
            //添加图片
            $zip->addFromString(basename($file), $fileContent);
        }
        // 关闭
        $zip->close();

        //没有文件
        if (!file_exists($zipNameUrl)) {
            return '下载失败，图片不存在或无法下载';
        }

        header("Cache-Control: public");
        header("Content-Description: File Transfer");
        header('Content-disposition: attachment; filename=' . $zipName); //文件名
        header("Content-Type: application/zip"); //zip格式的
        header("Content-Transfer-Encoding: binary"); //告诉浏览器，这是二进制文件
        header('Content-Length: ' . filesize($zipNameUrl)); //告诉浏览器，文件大小

        // 下面2步必须要
        ob_clean();
        flush();

        @readfile($zipNameUrl);
        unlink($zipNameUrl); // 删除文件
        exit;

    }
    
    /**
     * 判断文件是否存在，支持本地及远程文件
     * @param String $file 文件路径
     * @return Boolean
     */
    private function checkFileExists($file)
    {
        // 远程文件
        if (strtolower(substr($file, 0, 5)) == 'https') {
            // 远程文件
            $header = get_headers($file, true);
            return isset($header[0]) && (strpos($header[0], '200') || strpos($header[0], '304'));

        } elseif (strtolower(substr($file, 0, 4)) == 'http') {
            // 远程文件
            $header = get_headers($file, true);
            return isset($header[0]) && (strpos($header[0], '200') || strpos($header[0], '304'));
        } else {
            // 本地文件
            return file_exists($file);
        }
    }
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


}
